package com.project.myxima;

import android.content.Context;
import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;
import com.project.myxima.adapters.AlbumListAdapter;
import com.project.myxima.adapters.SuggestionAdapter;
import com.project.myxima.base.BaseActivity;
import com.project.myxima.interfaces.ISearchCallback;
import com.project.myxima.presenters.AlbumDetailPresenter;
import com.project.myxima.presenters.SearchPresenter;
import com.project.myxima.utils.LogUtils;
import com.project.myxima.views.FlowTextLayout;
import com.project.myxima.views.UILoader;
import com.ximalaya.ting.android.opensdk.model.album.Album;
import com.ximalaya.ting.android.opensdk.model.word.HotWord;
import com.ximalaya.ting.android.opensdk.model.word.QueryResult;

import net.lucode.hackware.magicindicator.buildins.UIUtil;

import java.util.ArrayList;
import java.util.List;


public class SearchActivity extends BaseActivity implements ISearchCallback, AlbumListAdapter.onRecommendItemClickListener {

    private static final String TAG = "SearchActivity";
    private ImageView mBackBtn;
    private EditText mSearchInput;
    private TextView mSearchBtn;
    private FrameLayout mResultContainer;
    private SearchPresenter mSearchPresenter = null;
    private FlowTextLayout mHotwordView;
    private UILoader mUILoader;
    private RecyclerView mResultRv;
    private AlbumListAdapter mAlbumListAdapter;
    private InputMethodManager mImm;
    private View mDeleteBtn;
    private static final int TIME_SHOW_IMM = 500;
    private RecyclerView mSuggestionList_rv;
    private SuggestionAdapter mSuggestionAdapter;
    private TwinklingRefreshLayout mRefreshLayout;
    private List<Album> mAlbumList = new ArrayList<>();


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);

        initView();
        initEvent();
        initPresenter();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mSearchPresenter != null) {
            mSearchPresenter.unregisterViewCallback(this);
            mSearchPresenter = null;
        }
    }

    private void initPresenter() {
        mImm = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
        mSearchPresenter = SearchPresenter.getSearchPresenter();
        mSearchPresenter.registerViewCallback(this);

        mSearchPresenter.getHotWord();

    }

    private void initEvent() {

        //click to jump to detail activity
        mAlbumListAdapter.setOnRecommendItemClickListener(this);


        //set listener for adapter
        if (mSuggestionAdapter != null) {
            mSuggestionAdapter.setOnItemClickListener(new SuggestionAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(String keyword) {
                    hideView();
                    mUILoader.updateStatus(UILoader.UIStatus.LOADING);
                    switch2Search(keyword);
                    LogUtils.d(TAG,"mSuggestionAdapter keyword---->" + keyword);
                }
            });
        }


        mBackBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        mSearchInput.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (TextUtils.isEmpty(s)) {
                    mSearchPresenter.getHotWord();
                    mDeleteBtn.setVisibility(View.GONE);
                }else{
                    hideView();
                    getSuggestion(s.toString());
                    mDeleteBtn.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        mSearchBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                String inputString = mSearchInput.getText().toString();
                if (mSearchPresenter != null) {


                    if(TextUtils.isEmpty(inputString)){
                        Toast.makeText(SearchActivity.this,"input something before search",Toast.LENGTH_SHORT).show();
                        return;
                    }
                    hideView();
                    mSearchPresenter.doSearch(inputString);

                    mUILoader.updateStatus(UILoader.UIStatus.LOADING);
                }
            }
        });

        mUILoader.setOnRetryClickListener(new UILoader.OnRetryClickListener() {
            @Override
            public void onRetryClick() {
                if (mSearchPresenter != null) {
                    mSearchPresenter.reSearch();
                    mUILoader.updateStatus(UILoader.UIStatus.LOADING);
                }
            }
        });

        mHotwordView.setClickListener(new FlowTextLayout.ItemClickListener() {
            @Override
            public void onItemClick(String text) {
                hideView();
                switch2Search(text);
            }

        });

        mDeleteBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mSearchInput.setText("");
            }
        });

        //refresh layout pull to refresh
        if (mRefreshLayout != null) {
            mRefreshLayout.setOnRefreshListener(new RefreshListenerAdapter() {
                @Override
                public void onLoadMore(TwinklingRefreshLayout refreshLayout) {
                    super.onLoadMore(refreshLayout);
                    mSearchPresenter.loadMore();
                    //Toast.makeText(SearchActivity.this,"pullUp to Load more",Toast.LENGTH_SHORT).show();

                }

                @Override
                public void onRefresh(TwinklingRefreshLayout refreshLayout) {
                    super.onRefresh(mRefreshLayout);

                }
            });
        }


    }

    private void switch2Search(String text) {

        if (mUILoader != null) {
            mUILoader.updateStatus(UILoader.UIStatus.LOADING);
        }
        if (mSearchPresenter != null) {
            mSearchInput.setText(text);
            mSearchInput.setSelection(text.length());
            mSearchPresenter.doSearch(text);
        }

    }

    private void getSuggestion(String keyword) {
        if (mSearchPresenter != null) {
            mSearchPresenter.getSuggestionWord(keyword);
        }

    }

    private void initView() {
        mBackBtn = this.findViewById(R.id.back_btn);
        mSearchInput = this.findViewById(R.id.search_input_et);
        //show the keyboard
        mSearchInput.postDelayed(new Runnable() {
            @Override
            public void run() {
                mSearchInput.requestFocus();
                mImm.showSoftInput(mSearchInput,InputMethodManager.SHOW_IMPLICIT);
            }
        },TIME_SHOW_IMM);

        mDeleteBtn = this.findViewById(R.id.search_input_delete);
        mDeleteBtn.setVisibility(View.GONE);

        mSearchBtn = this.findViewById(R.id.search_btn);
        mResultContainer = this.findViewById(R.id.search_container);
        mResultContainer.setVisibility(View.GONE);

        if (mUILoader == null) {
            mUILoader = new UILoader(this) {
                @Override
                protected View getSuccessView(ViewGroup container) {
                    return createSuccessView();
                }
            };
            //add to container
            if(mUILoader.getParent() instanceof ViewGroup){
                ((ViewGroup) mUILoader.getParent()).removeView(mUILoader);
            }
            mResultContainer.addView(mUILoader);
        }

        //flow text
        mHotwordView = this.findViewById(R.id.hot_word_view);
        mHotwordView.setVisibility(View.VISIBLE);

        //refresh layout
        mRefreshLayout = this.findViewById(R.id.search_refresh_layout);
        mRefreshLayout.setEnableRefresh(false);
    }

    private View createSuccessView() {
        View view = LayoutInflater.from(this).inflate(R.layout.search_result_layout,null);

        mResultRv = view.findViewById(R.id.result_list_rv);



        //adapter of mResultRv
        mAlbumListAdapter = new AlbumListAdapter();
        mResultRv.setAdapter(mAlbumListAdapter);
        //layout manager of mResultRv
        LinearLayoutManager manager = new LinearLayoutManager(this);
        mResultRv.setLayoutManager(manager);

        /*mResultRv.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
                outRect.top = UIUtil.dip2px(view.getContext(),5);
                outRect.bottom = UIUtil.dip2px(view.getContext(),5);
                outRect.left = UIUtil.dip2px(view.getContext(),5);
                outRect.right = UIUtil.dip2px(view.getContext(),5);
            }
        });*/

        //Suggestion list
        mSuggestionList_rv = view.findViewById(R.id.suggestion_list_rv);
        mSuggestionAdapter = new SuggestionAdapter();
        LinearLayoutManager manager1 = new LinearLayoutManager(this);
        mSuggestionList_rv.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
                outRect.top = UIUtil.dip2px(view.getContext(),2);
                outRect.bottom = UIUtil.dip2px(view.getContext(),2);
                outRect.left = UIUtil.dip2px(view.getContext(),5);
                outRect.right = UIUtil.dip2px(view.getContext(),5);
            }
        });
        mSuggestionList_rv.setAdapter(mSuggestionAdapter);
        mSuggestionList_rv.setLayoutManager(manager1);

        return view;
    }

    @Override
    public void onSearchResultLoaded(List<Album> result, boolean isLoadMore) {

        hideView();
        mResultContainer.setVisibility(View.VISIBLE);
        mRefreshLayout.setVisibility(View.VISIBLE);

        //hide the keyboard
        mImm.hideSoftInputFromWindow(mSearchInput.getWindowToken(),InputMethodManager.HIDE_NOT_ALWAYS);

        if(mUILoader != null && result.size()>0){
            if(isLoadMore){
                mAlbumList.addAll(result);
            }else {
                mAlbumList = result;
            }

            mAlbumListAdapter.setData(result);
            mAlbumListAdapter.notifyDataSetChanged();
            mUILoader.updateStatus(UILoader.UIStatus.SUCCESS);


        }else if(!isLoadMore && mUILoader != null ){
            mUILoader.updateStatus(UILoader.UIStatus.EMPTY);
        }else if(isLoadMore && result.size() ==0){
            Toast.makeText(this, "没有更多精彩内容", Toast.LENGTH_SHORT).show();
        }

        if(isLoadMore){
            mRefreshLayout.finishLoadmore();
        }

    }

    @Override
    public void onHotWordLoaded(List<HotWord> hotWordList) {

        hideView();
        mHotwordView.setVisibility(View.VISIBLE);
        List<String> hotwords = new ArrayList<>();
        hotwords.clear();
        for (HotWord word : hotWordList){
            String searchWord = word.getSearchword();
            hotwords.add(searchWord);
        }

        mUILoader.updateStatus(UILoader.UIStatus.SUCCESS);

        mHotwordView.setTextContents(hotwords);
    }

    @Override
    public void onLoadMoreResult(List<Album> result, boolean isOkay) {

    }

    @Override
    public void onSuggestionWordLoaded(List<QueryResult> keyWordList) {

        //todo:bug_有bug：在第二次修改输入框文字时，只显示之前的suggest word，点击时却发现是新的suggest word，不一致
        //hideView();
        mSuggestionList_rv.setVisibility(View.VISIBLE);
        mResultContainer.setVisibility(View.VISIBLE);

        if (mSuggestionAdapter != null) {
            mSuggestionAdapter.setData(keyWordList);
            //mSuggestionList_rv.setVisibility(View.VISIBLE);
            mSuggestionAdapter.notifyDataSetChanged();
        }


        //set UI status
        if (mUILoader != null) {
            mUILoader.updateStatus(UILoader.UIStatus.SUCCESS);
        }
    }

    private void hideView() {
        //mResultRv.setVisibility(View.GONE);
        mRefreshLayout.setVisibility(View.GONE);
        mHotwordView.setVisibility(View.GONE);
        mResultContainer.setVisibility(View.GONE);
        mSuggestionList_rv.setVisibility(View.GONE);
    }

    @Override
    public void onError(int errorCode, String errorMsg) {
        if (mUILoader != null) {
            mUILoader.updateStatus(UILoader.UIStatus.NETWORK_ERROR);
        }
    }

    @Override
    public void onItemClick(int position, Album album) {
        //get data by position
        AlbumDetailPresenter.getInstance().setTargetAlbum(album);
        //when it click item
        Intent intent = new Intent(this, DetailActivity.class);
        startActivity(intent);
    }
}
